from django.shortcuts import render
from rest_framework import permissions
from rest_framework.authentication import SessionAuthentication
from rest_framework_simplejwt.authentication import JWTAuthentication

# Create your views here.
from rest_framework.viewsets import ModelViewSet, GenericViewSet

from app.trade.models import ShoppingCart, OrderInfo, OrderGoods
from app.trade.serializers import ShoppingCartSerializer, ShoppingCartDetailSerializer, OrderInfoSerializer, \
    orderInfoDetailSerializer
from app.user_operate.authentication import IsOwnerOrReadOnly


class ShoppingCartView(ModelViewSet):
    authentication_classes = [JWTAuthentication, SessionAuthentication]
    permission_classes = [permissions.IsAuthenticated, IsOwnerOrReadOnly]
    lookup_field = 'goods_id'

    def get_queryset(self):
        return ShoppingCart.objects.filter(user=self.request.user)

    # 动态序列化
    def get_serializer_class(self):
        if self.action == 'retrieve':
            return ShoppingCartDetailSerializer
        else:
            return ShoppingCartSerializer


class OrderInfoView(ModelViewSet):
    authentication_classes = [JWTAuthentication, SessionAuthentication]
    permission_classes = [permissions.IsAuthenticated, IsOwnerOrReadOnly]

    # serializer_class = OrderInfoSerializer
    # 当创建订单的时候，需要将购物车清空，并加入到订单中
    def perform_create(self, serializer):
        order = serializer.save()
        # 计算总金额
        sum_money = 0
        # 查询该用户的购物车
        shopcarts = ShoppingCart.objects.filter(user=self.request.user)
        for shopcart in shopcarts:
            ordergoods = OrderGoods()
            ordergoods.goods = shopcart.goods
            ordergoods.goods_num = shopcart.nums
            ordergoods.order = order
            sum_money += shopcart.goods.shop_price * shopcart.nums
            ordergoods.save()
            shopcart.delete()
        order.order_mount = sum_money
        order.save()

    def get_queryset(self):
        return OrderInfo.objects.filter(user=self.request.user)

    def get_serializer_class(self):
        if self.action == 'retrieve':
            return orderInfoDetailSerializer
        else:
            return OrderInfoSerializer
